import pandas as pd
from datetime import datetime


def error2_idf(df,dict_info_setting, columns):
    """
    新版体重规则检查函数（兼容主程序样式系统）
    :param df: 原始数据 DataFrame
    :param columns: 需要检查的列名列表 [体重列, 建议列, BMI列]
    :return: (样式字典, 批注列表)
    """
    styles_info = {}
    comments_info = []


    BMI_Lweight_Uweight = [int(info.strip()) for info in dict_info_setting["error2_idf"].split(":")[-1].split(",")]

    # 解包列名参数
    weight_col, suggestion_col, bmi_col = columns

    for idx, row in df.iterrows():
        weight = row[weight_col]
        suggestion = row[suggestion_col]
        bmi = row[bmi_col]

        # 样式优先级字典（数值越大优先级越高）
        priority = {'warning': 1, 'error': 2, 'info': 0}
        current_styles = {}

        def update_style(col, new_style):
            """智能更新单元格样式，保留高优先级样式"""
            key = (idx, col)
            existing = styles_info.get(key, None)

            # 比较新旧样式优先级
            if not existing or priority.get(new_style, 0) > priority.get(existing, 0):
                styles_info[key] = new_style
                current_styles[col] = new_style  # 记录当前修改

        # 规则2：BMI与建议关联校验
        if pd.notna(bmi) and pd.notna(suggestion):
            if bmi > BMI_Lweight_Uweight[0]:
                lower = weight + BMI_Lweight_Uweight[1]
                upper = weight + BMI_Lweight_Uweight[2]
                valid_range = f"{lower}~{upper}kg"

                # 建议值校验
                if not (lower <= suggestion <= upper):
                    comments_info.append((idx, suggestion_col,
                                          f"建议体重应在{valid_range}（当前建议: {suggestion}kg）"))
                    update_style(suggestion_col, 'info')

                    # 关联标记体重列（不影响已存在的更高优先级样式）
                    if current_styles.get(weight_col) != 'warning':
                        update_style(weight_col, 'info')

    return styles_info, comments_info


